var mongoose = require('mongoose');
var Q = require('q');

const MAX_PAGE_SIZE = 100;   //每页最多多少条
const DEFAULT_ROWS = 5;  //默认请求的条数
const DEFAULT_START_PAGENO = 1;

var Schema = mongoose.Schema;
//定义了一个集合的数据结构(相当于一个表的字段)
//new Schema({...},{versionKey:'__someElse'});
var schemaUser = new Schema({
        userID: {
            type: 'String',
            required: true //userID 非空
        },
        userName: {
            type: 'String',
            required: true //userName 非空
        },
        nickname: {
            type: 'String',
            required: true //nickname 非空
        },
        pic: {
            type: 'String',
            default: null,
            required: false //pic 可以空
        },
        updated: {
            type: Date,
            default: Date.now
        },
        hasLogined: {
            type: Boolean,
            default: false
        }
    },
    //versionKey——版本锁
    {versionKey: '__'}
);

//定义 message 结构
var schemaMessage = new Schema({
    content: {
        type: 'String',
        required: true //内容 非空
    },
    type: {
        type: 'String',
        default: 'normal'
    },
    fromID: {
        type: 'String',
        required: true
    },
    from: {
        type: 'String',
        required: true
    },
    toID: {
        type: 'String',
        required: true
    },
    to: {
        type: 'String',
        required: true
    },
    timeStamp: {
        type: Date,
        default: Date.now
    }
});

//定义 log 结构,记录login logout情况
var schemaLog = new Schema({
    type: {
        type: 'String',
        required: true //type: "welcome", "bye"
    },
    userID: {
        type: 'String',
        required: true //userID 非空
    },
    userName: {
        type: 'String',
        required: true //userName 非空
    },
    timeStamp: {
        type: Date,
        default: Date.now
    }
});
//插入一条log
exports.insertLog = function (data) {
    console.log("insertLog");

    this.m = data;
    console.log(data);
    //防止错误时破坏数据
    if (this.m.userID == null || typeof (this.m.userID) == 'undefined') {
        console.log("缺少 userID ");
        return;
    }
    if (this.m.userName == null || typeof (this.m.userName) == 'undefined') {
        console.log("缺少 userName ");
        return;
    }

    var LogModel = mongoose.model('Log', schemaLog);
    var m = new LogModel;

    if (this.m.type == null || typeof (this.m.type) == 'undefined')
        m.type = 'unknown';
    else
        m.type = this.m.type;

    m.userID = this.m.userID;
    m.userName = this.m.userName;

    m.save(function (err) {
        if (err != null) {
            console.log("err888");
            console.log(err);
        }
    });

};

//插入一条消息
exports.insertMessages = function (message) {
    console.log("insertMessage");
    this.m = message;
    console.log(message);

    //防止错误时破坏数据
    if (this.m.content == null || typeof (this.m.content) == 'undefined') {
        console.log("缺少 content ");
        return;
    }
    if (this.m.fromID == null || typeof (this.m.fromID) == 'undefined') {
        console.log("缺少 fromID ");
        return;
    }
    if (this.m.from == null || typeof (this.m.from) == 'undefined') {
        console.log("缺少 from ");
        return;
    }

    var Message = mongoose.model('Messages', schemaMessage);
    var m = new Message;

    m.content = this.m.content;
    m.type = this.m.type;
    //先不要 m.color = this.m.color

    m.fromID = this.m.fromID;
    m.from = this.m.from;
    if (typeof (this.m.toID) == 'undefined' || this.m.toID == null) {
        //直接设置为 群聊 userID: 0, userName: "all", nickname: "所有人"
        m.toID = '0';
        m.to = 'all';
    }
    else {
        m.toID = this.m.toID;
        m.to = this.m.to;
    }


    console.log("mmmm==");
    console.log(m);

    m.save(function (err) {
        if (err != null) {
            console.log("err777");
            console.log(err);
        }
    });

};

/* unused
 exports.queryMessages = function (from, to) {
 var Message = mongoose.model('Messages', schemaMessage);
 //var m = new Message;

 //直接找到一条数据,因为userName 是唯一的
 var x = 'wzh';
 var where = {'userName': x}; //查询条件
 //var projection = {'userID':1,'userName':1,'_id':0};//返回哪些字段,不包括_id
 // var projection = {'_id': 0};//返回所有字段,除了_id
 var query = Message.find({bar: true});
 var promise = query.exec();

 return promise;
 };
 */

//输出(对外暴露)一个函数 insertUser
insertUser = function (mUser) {
    console.log("insertUser");
    this.m = mUser;

    var User = mongoose.model('Users', schemaUser);
    var m = new User;

    m.userID = this.m.userID;
    m.userName = this.m.userName;
    m.nickname = this.m.nickname;
    console.log(m);

    m.save(function (err) {
        if (err != null) {
            console.log("err666");
            console.log(err);
        }
    });


};
exports.insertUser = insertUser;

//几条初始化数据,放在一个对象数组里面,测试时可以直接循环全部插入,
initUser = function () {
    //应该使用 判断 collection 是否存在来处理,待处理
    queryByUserName('wzh').then(function () {
            //已经存在,就不再 init 了
            console.log("------已完成过,无需再次初始化------");
        }
        , function () {
            var users = [
                {
                    userID: "13501062476",
                    userName: 'wzh',
                    nickname: '汪志洪'
                },
                {
                    userID: "13901058301",
                    userName: 'cjq',
                    nickname: '陈军前'
                },
                {
                    userID: "13439475146",
                    userName: 'mlj',
                    nickname: '小马'
                },
                {
                    userID: "13522388251",
                    userName: 'zxc',
                    nickname: '祥子'
                }
            ];

            for (var i = 0; i < users.length; i++) {
                var insertUser123 = insertUser(users[i]);
            }

            console.log("------第一次初始化成功！------");
        }
    );

};
exports.initUser = initUser;

//查询这个用户信息
exports.queryUser = function (mUser) {
    var deferred = Q.defer();
    if (!dbConnected) {
        //数据库错误,直接返回
        console.log('数据库错误,直接返回 =');
        deferred.reject("<h1> 数据库错误,请检查数据库服务器是否开启</h1>");
        return deferred.promise;
    }
    ;

    var User = mongoose.model('Users', schemaUser);

    //直接找到一条数据,因为userName 是唯一的
    var userName = mUser.userName;
    var where = {'userName': userName}; //查询条件
    //var projection = {'userID':1,'userName':1,'_id':0};//返回哪些字段,不包括_id
    var projection = {'_id': 0};//返回所有字段,除了_id

    User.findOne(where, projection, function (err, user) {
        if (err == null) {
            deferred.resolve(user);
        }
        else {
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;

};

queryByUserName = function (userName) {
    var deferred = Q.defer();
    if (!dbConnected) {
        //数据库错误,直接返回
        console.log('数据库错误,直接返回 =');
        deferred.reject("<h1> 数据库错误,请检查数据库服务器是否开启</h1>");
        return deferred.promise;
    }
    ;

    var User = mongoose.model('Users', schemaUser);

    //直接找到一条数据,因为userName 是唯一的
    var where = {'userName': userName}; //查询条件
    //var projection = {'userID':1,'userName':1,'_id':0};//返回哪些字段,不包括_id
    var projection = {'_id': 0};//返回所有字段,除了_id

    //findOne 本身可以直接作为 promise返回,但是会和mongoose的promise 有冲突
    //Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
    promise = User.findOne(where, projection, function (err, user) {
        if (err == null) {
            if (user == null || user.length < 1) {
                //查询动作是成功的,但是,结果是空的,我这里给他 reject表示没有找到
                deferred.reject('error!No user');
            }
            else
                deferred.resolve(user);
        }
        else {
            console.log("222");
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;

};
exports.queryByUserName = queryByUserName;

//查询用户信息
exports.queryUsers = function (page, rows) {
    var deferred = Q.defer();
    if (!dbConnected) {
        //数据库错误,直接返回
        console.log('数据库错误,直接返回 =');
        deferred.reject("<h1> 数据库错误,请检查数据库服务器是否开启</h1>");
        return deferred.promise;
    }
    ;

    var Users = mongoose.model('Users', schemaUser);

    var where = {}; //查询条件     //找到所有数据
    var projection = {'_id': 0};//返回所有字段,除了_id

    if (page <= 0 || typeof(page) == 'undefined') page = DEFAULT_START_PAGENO;
    if (rows <= 0 || typeof(rows) == 'undefined') rows = DEFAULT_ROWS;
    if (rows > MAX_PAGE_SIZE) rows = MAX_PAGE_SIZE;

    var query = Users.find(where);
    //跳过 前面页的记录
    query.skip((page - 1) * rows);
    //限制总共获取的条数
    query.limit(rows);

    query.exec(function (err, users) {
        if (err == null) {
            deferred.resolve(users);
        }
        else {
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;
};

//查询聊天信息:需要哪一页?多少条?
exports.queryMessages = function (page, rows) {
    var deferred = Q.defer();
    if (!dbConnected) {
        //数据库错误,直接返回
        console.log('数据库错误,直接返回 =');
        deferred.reject("<h1> 数据库错误,请检查数据库服务器是否开启</h1>");
        return deferred.promise;
    }
    ;

    var Messages = mongoose.model('Messages', schemaMessage);
    var where = {}; //查询条件     //找到所有数据
    var projection = {'_id': 0};//返回所有字段,除了_id

    if (page <= 0 || typeof(page) == 'undefined') page = DEFAULT_START_PAGENO;
    if (rows <= 0 || typeof(rows) == 'undefined') rows = DEFAULT_ROWS;
    if (rows > MAX_PAGE_SIZE) rows = MAX_PAGE_SIZE;

    var query = Messages.find(where);
    //跳过 前面页的记录
    query.skip((page - 1) * rows);
    //限制总共获取的条数
    query.limit(rows);

    query.exec(function (err, messages) {
        if (err == null) {
            console.log("找到了messages：");
            //console.log(messages);
            deferred.resolve(messages);
        }
        else {
            //console.log("没有找到聊天信息");
            //console.log(messages);
            deferred.reject('error!No messages');
        }
    });

    return deferred.promise;
};

//(node:759) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated,
// plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

var db = mongoose.connect('mongodb://127.0.0.1/chat2016062402');//；连接数据库
var dbConnected = false;

db.connection.on("error", function (error) {
    console.log("数据库连接失败：" + error);
    dbConnected = false;
});
db.connection.on("open", function () {
    console.log("------数据库连接成功！------");
    dbConnected = true;
});

//初始化一次
db.connection.once("open", initUser);

